<template>
  <div class="box">
    <!-- 遍历shopcar -->
    <Item v-for="data in shopCar" :key="data.id" v-bind="data" :increase="increase" :decrease="decrease" />
    <hr>
    一共有{{total}}件商品
  
  </div>
</template>


<script>
import Item from "./components/Item.vue"
import {nanoid} from "nanoid"

export default {
  name:"App",
components:{
  Item
},
data(){
  return {
    shopCar:[
      {
        id:nanoid(),
        name:"iphone14",
        desc:"more strong",
        num:1
      },
      {
        id:nanoid(),
        name:"小米",
        desc:"xiaomi",
        num:2
      },
      {
        id:nanoid(),
        name:"华为",
        desc:"huaweiP40",
        num:3
      }

    ]
  }
},
computed:{
  // 计算一共有多少件商品
  total(){
    return this.shopCar.reduce((p,c)=> p + c.num,0)
  }
},
methods:{
  // 点击按钮 增加和减少商品数量 将函数传给子组件 子组件调用函数传id
  increase(id){
    this.shopCar.forEach((item)=>{
    if(item.id === id){
      item.num++
    }
    })
  },
  decrease(id){
   this.shopCar.forEach((item)=>{
    if(item.id === id){
      item.num--
    }
    })
  }
}

}
</script>

<style>
  /* .box{
    background: lightblue;
  } */
</style>